package cn.buk.tms.dao;

import cn.buk.common.util.DateUtil;
import cn.buk.tms.entity.misc.*;
import cn.buk.tms.entity.order.OrderAttachment;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static cn.buk.tms.entity.config.EnterpriseConfig.MAX_SEARCHABLE_YEARS;

/**
 * @author yfdai
 */
public abstract class AbstractDao {

	public static final Logger logger = LogManager.getLogger(AbstractDao.class);

	@PersistenceContext(unitName = "qms")
	protected EntityManager em;

	protected EnterpriseBalance doGetEnterpriseBalance(final int enterpriseId, EntityManager em) {
		return doGetEnterpriseBalance(Enterprise.ENTERPRISE_PLATFORM_ADMINISTRATOR, enterpriseId, em);
	}

	/**
	 * 获取指定企业的账户余额
	 * @param authorizer0 授权者
	 * @param enterpriseId 被授权
	 * @return
     */
	protected EnterpriseBalance doGetEnterpriseBalance(final int authorizer0, final int enterpriseId, EntityManager em) {
		EnterpriseBalance result = null;

		final int authorizer = authorizer0 == 0 ? Enterprise.ENTERPRISE_PLATFORM_ADMINISTRATOR : authorizer0;

		logger.debug("doGetEnterpriseBalance: " + enterpriseId + ", " + authorizer0 + ", " + authorizer);

		// 如果 被授权者不是 授权者的下级客户，则不应该有
		if (authorizer0 > 0 && authorizer0 != Enterprise.ENTERPRISE_PLATFORM_ADMINISTRATOR && authorizer != enterpriseId) {
			//检查 被授权者是不是授权者的下级客户
			Enterprise ent = em.find(Enterprise.class, enterpriseId);
			if (ent == null || ent.getParentEnterprise() != authorizer0) {
				return null;
			}
		}

		List<EnterpriseBalance> results = em.createQuery("select o from EnterpriseBalance o " +
				"where o.enterpriseId = :enterpriseId and o.authorizer = :authorizer", EnterpriseBalance.class)
				.setParameter("enterpriseId", enterpriseId)
				.setParameter("authorizer", authorizer)
				.getResultList();

		if (results.size() > 0) {
			result = results.get(0);
		} else {
			result = new EnterpriseBalance();
			result.setEnterpriseId(enterpriseId);
			result.setAuthorizer(authorizer);
			em.persist(result);
		}

		return result;
	}

	/**
	 * 查询订单日志
	 * @param enterpriseId
	 * @param orderType
	 * @param orderId
	 * @return
	 */
	protected List<OperationLog> searchOrderHistory(final int enterpriseId, final int orderType, final int orderId) {
		return em.createQuery("select o from OperationLog o where o.enterpriseId = :enterpriseId and o.objectType = :ot and o.orderId = :orderId order by o.id desc", OperationLog.class)
				.setParameter("enterpriseId", enterpriseId)
				.setParameter("ot", orderType)
				.setParameter("orderId", orderId)
				.getResultList();
	}

	protected int saveOrderAttachment(final int enterpriseId, final String username,
																 final int orderType, final int orderId, List<OrderAttachment> attachments) {
		String content = null;
		for(OrderAttachment oa: attachments) {
			em.persist(oa);
			if (content == null) {
				content = oa.getFileName();
			} else
				content += ", " + oa.getFileName();
		}

		OperationLog log = new OperationLog();
		log.setObjectType(orderType);
		log.setOperator(username);
		log.setOrderId(orderId);
		log.setEnterpriseId(enterpriseId);
		log.setContent("上传附件: " + content);
		em.persist(log);

		return log.getId();
	}

	protected List<OrderAttachment> searchAttachments(final int enterpriseId, final int orderType, final int orderId) {
		return em.createQuery("select o from OrderAttachment o " +
						"where o.enterpriseId = :enterpriseId " +
						"and o.orderType = :orderType " +
						"and o.orderId = :orderId order by o.id", OrderAttachment.class)
						.setParameter("enterpriseId", enterpriseId)
						.setParameter("orderType", orderType)
						.setParameter("orderId", orderId)
						.getResultList();
	}

	protected List<TicketSale> searchTicketSale(int enterpriseId, String ticketNo, int ticketStatus) {
		return em.createQuery("select o from TicketSale o " +
						"where o.enterpriseId = :enterpriseId " +
						"and o.ticketNo = :ticketNo " +
						"and o.ticketStatus = :ticketStatus", TicketSale.class)
						.setParameter("enterpriseId", enterpriseId)
						.setParameter("ticketNo", ticketNo)
						.setParameter("ticketStatus", ticketStatus)
						.getResultList();
	}


	protected List<Integer> searchCustomerIdsLikeName(final int enterpriseId, final String likeName) {
		List<Integer> customerIds = null;
		if (StringUtils.isNotBlank(likeName)) {
			//启用的客户姓名或编码的模糊查找
			customerIds = em.createQuery("select o.id from Customer o " +
							"where o.enterpriseId = :enterpriseId " +
							"and (o.vipName like :name or o.customerCode like :name)", Integer.class)
							.setParameter("enterpriseId", enterpriseId)
							.setParameter("name", "%" + likeName.trim().toUpperCase() + "%")
							.getResultList();
		} else {
			customerIds = new ArrayList<>();
		}

		return customerIds;
	}

	/**
	 * 默认订单能查询的最早订单时间
	 * @return
	 */
	protected Date getMinBeginDate() {
		int days = -(MAX_SEARCHABLE_YEARS > 0 ? MAX_SEARCHABLE_YEARS : 5) * 365;
		return DateUtil.addDays(DateUtil.getCurDate(), days);
	}

}
